package org.petstore.persistence.impl;

import org.petstore.domain.ShoppingCart;
import org.petstore.persistence.ItemDAO;
import org.petstore.persistence.ShoppingCartDAO;
import org.petstore.persistence.util.JDBCUtils;
import org.petstore.util.CartItem;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

public class ShoppingCartDAOImpl implements ShoppingCartDAO {

    private final JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    private static final String DELETE_CART = "DELETE FROM SHOPPINGCART WHERE USERNAME =? AND INSTOCK  =0";
    private static final String INSERT_CART = "INSERT INTO SHOPPINGCART(USERNAME,ITEMID,QUANTITY,INSTOCK,TOTAL)VALUES(?,?,?,?,?)";
    private static final String SELECT_CART = "SELECT * FROM SHOPPINGCART WHERE USERNAME=? AND INSTOCK = 0";
    private static final String UPDATE_CART = "UPDATE SHOPPINGCART SET INSTOCK = 1 WHERE USERNAME =?";

    //INSTOCK列中 0表示该商品在售
    @Override
    public void store(String username, List<CartItem> list) {
        if (list != null) {
            template.update(DELETE_CART, username);
        }
        for (CartItem cartItem : list) {
            if (cartItem.getQuantity() != 0) {
                BigDecimal tmpQuantity = new BigDecimal(cartItem.getQuantity());
                BigDecimal total = cartItem.getItem().getListPrice().multiply(tmpQuantity);
                template.update(INSERT_CART, username, cartItem.getItem().getItemId(), cartItem.getQuantity(), 0, total.setScale(2, RoundingMode.HALF_UP));
            }
        }
    }

    @Override
    public void deleteCart(String username) {
        int count = template.update(UPDATE_CART, username);
    }

    @Override
    public List<CartItem> getCart(String username) {
        return null;
    }

    //获取某个用户的购物车信息
    @Override
    public List<CartItem> getCartList(String username) {

        List<CartItem> list = new ArrayList<>();
        try {
            List<ShoppingCart> list1 = template.query(SELECT_CART, new BeanPropertyRowMapper<>(ShoppingCart.class), username);
            for (ShoppingCart shopping_cart : list1) {
                CartItem cartItem = new CartItem();
                ItemDAO itemDAO = new ItemDAOImpl();
                cartItem.setItem(itemDAO.getItem(shopping_cart.getItemId()));
                cartItem.setInStock(true);
                cartItem.setQuantity(shopping_cart.getQuantity());
                list.add(cartItem);
            }
        } catch (DataAccessException e) {
            list = null;
        }
        return list;
    }


}
